package com.work.controller;

import com.github.pagehelper.PageInfo;
import com.work.pojo.Address;
import com.work.pojo.Cart;
import com.work.pojo.User;
import com.work.service.CartService;
import com.work.service.impl.CartServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @RequestMapping("/getCart")
    public ModelAndView getCart(ModelAndView modelAndView, HttpSession session) {
        User user = (User) session.getAttribute( "user" );
        Integer uid = user.getId();
        List<Cart> list = cartService.getCart( uid );
        Iterator<Cart> iterator = list.iterator();
        while (iterator.hasNext()) {
            Cart next = iterator.next();
            System.out.println( next );
        }
        modelAndView.addObject( "carts", list );
        modelAndView.setViewName( "forward:/cart.jsp" );
        return modelAndView;
    }

    @RequestMapping("/addCart")
    public ModelAndView addCart(ModelAndView modelAndView, HttpSession session, String goodsId, String number) {
        User user = (User) session.getAttribute( "user" );
        Integer uid = user.getId();
        Cart cart = new Cart();
        cart.setId( uid );
        cart.setNum( Integer.parseInt( number ) );
        cart.setPid( Integer.parseInt( goodsId ) );
        cartService.addCart( cart );
        modelAndView.setViewName( "forward:/cartSuccess.jsp" );
        return modelAndView;
    }

    @RequestMapping("/addCartAjax")
    public void addCartAjax(HttpSession session, Integer goodsId, Integer number) {
        User user = (User) session.getAttribute( "user" );
        Integer uid = user.getId();
        cartService.addCartAjax( uid, number, goodsId );
    }

    @RequestMapping("/clearCartAjax")
    public void clearCartAjax(HttpSession session) {
        User user = (User) session.getAttribute( "user" );
        Integer uid = user.getId();
        cartService.clearCartAjax( uid );
    }

    @RequestMapping("/getOrderView")
    public ModelAndView getOrderView(HttpSession session, ModelAndView modelAndView) {
        User user = (User) session.getAttribute( "user" );
        Integer uid = user.getId();
        List<Cart> list = cartService.getCart( uid );
        List<Address> addresses = cartService.getAddress( uid );
        modelAndView.addObject( "carts", list );
        modelAndView.addObject( "addList", addresses );
        modelAndView.setViewName( "forward:/order.jsp" );
        return modelAndView;
    }


}
